// 用来处理导航条的
function FontBase () {

}

FontBase.prototype.listenAuthBoxHover = function () {
    var authBox = $('.auth-box');
    var userMoreBox = $('.user-more-box');
    authBox.hover(function () {
        userMoreBox.show();
    },function () {
        userMoreBox.hide();
    });
};

FontBase.prototype.handelNavStatus = function () {
    // 获取域名地址，如：http://127.0.0.1:9000/course/
    var url = window.location.href;
    // 获取协议，如：http:
    var protocol = window.location.protocol;
    // 获取主机地址，如127.0.0.1:8000
    var host = window.location.host;
    // 获取http:127.0.0.1
    var domain = protocol + '//' + host;
    // 获取/course/
    var path = url.replace(domain,'');
    // 获取所有的li对象
    var navLis = $(".nav li");
    // 遍历所有的li,获取到的是js对象
    navLis.each(function (index, element) {
        // 得到所有的li标签
        var li = $(element);
        // 获取li下面的a标签
        var aTags = li.children('a');
        // 获取a标签的href属性值
        var href = aTags.attr('href');
        if(href===path){
            li.addClass('active');
            return false;
        }

    })
};

FontBase.prototype.run = function () {
    var self = this;
    self.listenAuthBoxHover();
    self.handelNavStatus()
};


// 用来处理登录的
function Auth() {
    var self = this;
    self.maskWrapper = $('.mask-wrapper');
    self.closeBtn = $('.close-btn');
    self.scrollWrapper = $(".scroll-wrapper");
    self.smsCaptcha = $(".sms-captcha-btn");
};

Auth.prototype.run = function () {
    var self = this;
    self.listenShowHideEvent();
    self.listenSwitchEvent();
    self.listenSigninEvent();
    self.listenImgCaptchaEvent();
    self.listenSmsCaptchaEvent();
    self.listenSignupEvent();
};

Auth.prototype.showEvent = function () {
    var self = this;
    self.maskWrapper.show();
};

Auth.prototype.hideEvent = function () {
    var self = this;
    self.maskWrapper.hide();
};

Auth.prototype.listenShowHideEvent = function () {
    var self = this;
    var signinBtn = $('.signin-btn');
    var signupBtn = $(".signup-btn");
    var closeBtn =$('.close-btn');
    signinBtn.click(function () {
        self.showEvent();
        self.scrollWrapper.css({"left":0});
    });
    signupBtn.click(function () {
        self.showEvent();
        self.scrollWrapper.css({'left':-400});
    });
    closeBtn.click(function () {
        self.hideEvent();
    });
};

Auth.prototype.listenSwitchEvent = function () {
    var self = this;
    var switcher = $(".switch");
    switcher.click(function () {
        // 获取这个元素的“left”
        var currentLeft = self.scrollWrapper.css("left");
        // 将“left”转换为整型，方便运算
        currentLeft = parseInt(currentLeft);
        if(currentLeft<0){
            // animated这个函数会使过度有个时间，而css函数会使过度没时间，体验效果不好
            self.scrollWrapper.animate({"left":"0"});
        }else{
            self.scrollWrapper.animate({"left":"-400px"});
        }
    });
};

Auth.prototype.listenSigninEvent = function () {
    var self = this;
    var signinGroup =$(".signin-group");
    var telephoneInput = signinGroup.find("input[name='telephone']");
    var passwordInput = signinGroup.find("input[name='password']");
    var rememberInput = signinGroup.find("input[name='remember']");
    var submitInput = signinGroup.find(".submit-btn");
    submitInput.click(function () {
        var telephone = telephoneInput.val();
        var password = passwordInput.val();
        // checkbox需要这样获取数据
        var remember = rememberInput.prop('checked');

        xfzajax.post({
            'url':'/account/login/',
            'data':{
                'telephone':telephone,
                'password':password,
                // remember值是1还是0
                'remember':remember?1:0
            },
            // result是返回值有code,message,data
            'success':function (result) {
                self.hideEvent();
                window.location.reload();
            }
        });
    });
};

Auth.prototype.listenSignupEvent = function () {
    var self = this;
    var signupGroup = $('.signup-group');
    var submitBtn = signupGroup.find(".submit-btn");
    submitBtn.click(function (event) {
        // 如果在form表单中，这个可以是提交按钮不生效
        event.preventDefault();
        // 获取各个input框
        var telephoneInput = signupGroup.find('input[name="telephone"]');
        var usernameInput = signupGroup.find('input[name="username"]');
        var password1Input = signupGroup.find('input[name="password1"]');
        var password2Input = signupGroup.find('input[name="password2"]');
        var imgCaptchaInput = signupGroup.find('input[name="img_captcha"]');
        var smsCaptchaInput = signupGroup.find('input[name="sms_captcha"]');
        // 获取各个input框的值
        var telephone = telephoneInput.val();
        var username = usernameInput.val();
        var password1 = password1Input.val();
        var password2 = password2Input.val();
        var imgCaptcha = imgCaptchaInput.val();
        var smsCaptcha = smsCaptchaInput.val();

        xfzajax.post({
            'url': 'account/register/',
            'data': {
                'telephone': telephone,
                'username': username,
                'password1': password1,
                'password2': password2,
                'img_captcha': imgCaptcha,
                'sms_captcha': smsCaptcha
            },
            'success': function (result) {
                // self.hideEvent();
                window.location.reload();
            }
        })
    })
};


// 监听验证图片的点击事件
Auth.prototype.listenImgCaptchaEvent = function () {
    var imgCaptcha = $(".img_captcha");
    imgCaptcha.click(function () {
        imgCaptcha.attr('src','account/img_captcha/'+'?random='+Math.random());
    });
};

// 短信发送成功后处理方法
Auth.prototype.smsSuccessEvent = function () {
    var self = this;
    // 增加提示
    messageBox.showSuccess('短信验证码发送成功！');
    // 给smsCaptcha按钮增加class='disable'
    self.smsCaptcha.addClass('disabled');
    // 添加倒计时
    var count = 60;
    // 使不能点击
    self.smsCaptcha.unbind('click');
    // 增加计时器，间隔1000毫秒
    var timer = setInterval(function () {
        // 改变按钮的显示
        self.smsCaptcha.text(count+'s');
        count --;
        if(count<=0){
            clearInterval(timer);
            self.smsCaptcha.removeClass('disable');
            self.smsCaptcha.text('发送验证码');
            self.listenSmsCaptchaEvent();
        }
    },1000);
};


// 监听手机验证码时间
Auth.prototype.listenSmsCaptchaEvent = function () {
    var self = this;

    var telephoneInput = $('.signup-group input[name="telephone"]');
    self.smsCaptcha.click(function () {
        var telephone = telephoneInput.val();
        if (!telephone){
            messageBox.showInfo('请输入手机号码！');
        }
        xfzajax.get({
            'url':'account/sms_captcha/',
            'data':{
                'telephone':telephone
            },
            'success':function (result) {
                console.log(result['code']);
                if(result['code']==200){
                    self.smsSuccessEvent();
                }
            },
            'fail':function () {
                messageBox.showError('发送失败');
            }

        })
    });
};

$(function () {
    var auth = new Auth();
    auth.run()
});

$(function () {
    var fontBase = new FontBase();
    fontBase.run();
});

$(function () {
   if(window.template){
       // 添加时间处理
        template.defaults.imports.timeSince = function (dataValues) {
            var date = new Date(dataValues);   //传进来的数据
            var datets = date.getTime() ;  //获取保存数据的时间，获得的是毫秒
            var nowts = new Date().getTime();        //获取当前的时间，获得的是毫秒
            var timestamp = (nowts - datets)/1000;    //得到时间戳，以秒为单位
            if(timestamp < 60) {
                return '刚刚'
            }else if (timestamp >= 60 && timestamp < 60*60){
                minutes = parseInt(timestamp/60);
                return minutes+'分钟前'
            }else if (timestamp >= 60*60 && timestamp < 60*60*24){
                hours = parseInt(timestamp/60/60);
                return hours+'小时前'
            }else if (timestamp >= 60*60*24 && timestamp < 60*60*24*30) {
                days = parseInt(timestamp / 60 / 60 / 24);
                return days+'天前'
            }else{
                var year = date.getFullYear();
                var month = date.getMonth();
                var day = date.getDay();
                var hours = date.getHours();
                var minite = date.getMinutes();
                return year+'/'+month+'/'+day+'/'+hours+':'+minite
            }
        }
   }
});